import math
import os
import sys
import time

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from src.db.CcxDataCenterDb import CcxDataCenter
from src.db.ProdDb import ProdDb
from src.utils.LogUtils import Logger

logger = Logger()


class syncQeResult:
    def __init__(self, logger, localDb, dataCenterDb):
        self.logger = logger
        self.localDb = localDb
        self.dataCenterDb = dataCenterDb

    def __queryMaxTime__(self):
        sql = """SELECT max(last_edit_time) as last_edit_time  FROM region_qe_result  WHERE release_status = 1 AND `status` = 1 AND ver = 0 ORDER BY last_edit_time DESC"""
        return self.localDb.Query(sql, None)

    def __queryCityInvestQe__(self, maxTime):
        sql = """SELECT * FROM region_qe_result WHERE release_status = 1 AND `status` = 1 AND ver = 0 AND 
        last_edit_time > %s"""
        if maxTime[0]["last_edit_time"] == None:
            last_edit_time = 0
        else:
            last_edit_time = maxTime[0]["last_edit_time"]
        self.logger.info("数据最大时间=======%s" % last_edit_time)
        return self.dataCenterDb.Query(sql, last_edit_time)

    def __regionQeDetail__(self, resultId):
        sql = """
            SELECT * FROM region_qe_result_data where result_id = %s
        """
        return self.dataCenterDb.Query(sql, resultId)

    def __deleteRegionQeResult__(self):
        sql = """
        DELETE from region_qe_result  
        """
        return self.localDb.Query(sql, None)

    def __deleteRegionQeResultData__(self):
        sql = """
        DELETE from region_qe_result_data  
        """
        return self.localDb.Query(sql, None)

    def __save_db__(self, data):
        regionSql = """
        REPLACE INTO  region_qe_result 
            (id,code,result_id,region_id,year,region_rank,region_rank_score,bca_level,sign,param,anchor_level,release_status,last_release_time,last_release_user,last_edit_time,last_edit_user,ver,status)
            VALUES
            (%(id)s,%(code)s,%(result_id)s,%(region_id)s,%(year)s,%(region_rank)s,%(region_rank_score)s,%(bca_level)s,%(sign)s,%(param)s,%(anchor_level)s,
            %(release_status)s,%(last_release_time)s,%(last_release_user)s,%(last_edit_time)s,%(last_edit_user)s,%(ver)s,%(status)s);
        """

        regionDetailSql = """
        REPLACE INTO  region_qe_result_data 
            (id,result_id,region_id,parent,code,name,value,score,proportion,range_index,ranges,version,type,indicator_type,ver,release_time,update_time,create_time)
            VALUES
            (%(id)s,%(result_id)s,%(region_id)s,%(parent)s,%(code)s,%(name)s,%(value)s,%(score)s,%(proportion)s,%(range_index)s,%(ranges)s,
            %(version)s,%(type)s,%(indicator_type)s,%(ver)s,%(release_time)s,%(update_time)s,%(create_time)s);
        """

        temp = []
        detailData = []
        for i in data:
            data = {
                "id": i["id"],
                "code": i["code"],
                "result_id": i["result_id"],
                "region_id": i["region_id"],
                "year": i["year"],
                "region_rank": i["region_rank"],
                "region_rank_score": i["region_rank_score"],
                "bca_level": i["bca_level"],
                "sign": i["sign"],
                "param": i["param"],
                "anchor_level": i["anchor_level"],
                "release_status": i["release_status"],
                "last_release_time": i["last_release_time"],
                "last_release_user": i["last_release_user"],
                "last_edit_time": i["last_edit_time"],
                "last_edit_user": i["last_edit_user"],
                "ver": i["ver"],
                "status": i["status"],
            }
            # 区域数据
            temp.append(data)
            # 区域详情数据
            resultId = i["result_id"]
            if resultId == None:
                resultId = 0
            detail = self.__regionQeDetail__(resultId)
            for b in detail:
                detail = {
                    "id": b["id"],
                    "result_id": b["result_id"],
                    "region_id": b["region_id"],
                    "parent": b["parent"],
                    "code": b["code"],
                    "name": b["name"],
                    "value": b["value"],
                    "score": b["score"],
                    "proportion": b["proportion"],
                    "range_index": b["range_index"],
                    "ranges": b["ranges"],
                    "version": b["version"],
                    "type": b["type"],
                    "indicator_type": b["indicator_type"],
                    "ver": b["ver"],
                    "release_time": b["release_time"],
                    "update_time": b["update_time"],
                    "create_time": b["create_time"],
                }
                detailData.append(detail)

        logger.info("详情数据一共%s条" % len(detailData))
        self.localDb.ExecMany(regionDetailSql, detailData, 1000)
        logger.info("数据一共%s条" % len(temp))
        self.localDb.ExecMany(regionSql, temp, 1000)


if __name__ == "__main__":
    logger = Logger()
    localDb = ProdDb(logSql=False, autocommit=True)
    dataCenterDb = CcxDataCenter(logSql=False, autocommit=True)
    t = time.perf_counter()
    logger.info("========同步区域qe数据 开始 ========")
    syncData = syncQeResult(logger=logger, localDb=localDb, dataCenterDb=dataCenterDb)
    syncData.__deleteRegionQeResult__()
    syncData.__deleteRegionQeResultData__()
    # 最大时间
    maxId = syncData.__queryMaxTime__()
    data = syncData.__queryCityInvestQe__(maxId)
    syncData.__save_db__(data)
    cast = (time.perf_counter() - t)
    m = math.floor(cast / 60)
    s = cast - m * 60
    logger.info('总耗时: %d分%.3f秒' % (m, s))
    logger.info("========同步区域qe数据 结束 ========")
